package com.heima.article.service.Impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;


@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {

    @Autowired
    Configuration configuration;

    @Autowired
    AuthorMapper authorMapper;

    @Autowired
    @Qualifier("minIOFileStorageService")
    FileStorageService fileStorageService;

    @Autowired
    ApArticleMapper apArticleMapper;

    @Value("${file.minio.prefix}")
    String prefix;

    @Value("${file.minio.readPath}")
    String readPath;





    /**
     * 生成静态页的方法
     * @param content
     * @param apArticle
     */
    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {
        try {
            //1.获取模板对象article.ftl
            Template template = configuration.getTemplate("article.ftl");
            //2.准备替换模板的数据  Map
            Map params = new HashMap();
            //   authorApUserId  文章作者对应的ap_user id
            ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
            params.put("authorApUserId",apAuthor.getUserId());
            //  article  文章对象
            params.put("article",apArticle);
            // content  文章详情  list<Map>
            params.put("content", JSON.parseArray(content,Map.class));
            //3. 替换模板生成静态页
            StringWriter writer = new StringWriter();
            template.process(params,writer);
            //4.将静态页 上传到minIO中
                //封装输入流  用于上传到minIO中
            ByteArrayInputStream inputStream = new ByteArrayInputStream(writer.toString().getBytes());
                //文章的id.html
            String minioPath = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", inputStream);
            //5. 将静态页在minio中的路径 设置到article的static_url字段上
            apArticle.setStaticUrl(minioPath);
            apArticleMapper.updateById(apArticle);
            log.info("成功生成 文章静态页=======》 地址： {}",readPath + minioPath);

        } catch (IOException | TemplateException e) {
            e.printStackTrace();
            log.error("生成文章静态页失败 =======》 原因： {}",e.getMessage());
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"生成静态页失败");
        }
    }
}
